<?php


namespace app\index\service;

use app\madmin\model\IntegralClassify;
use think\Exception;
use app\index\model\{IntegralRecord,
    Merchant,
    Store,
    User,
    UserAddress,
    IntegralGoods,
    Area,
    IntegralOrder,
    UserCash,
    IntegralSkuInventory};
use app\index\util\CreateNo;
use think\exception\HttpException;


class IntegralShopSerivce
{
    protected $user,$mid;
    public function __construct()
    {
        global $user,$mid;
        $this->mid = $mid;
        $this->user = User::find($user['id']);
    }

    public function classList(){
        return [HTTP_SUCCESS,IntegralClassify::where('mall_id',$this->mid)->select()];
    }


    public function goodsList(int $page,int $size,array $data) : array{
        global $mid;
        !empty($data['classify_id']) && $where[] = ['classify_id','=',$data['classify_id']];
        $where[] = ['mall_id','=',$mid];
        $list = IntegralGoods::where($where)
            ->where('status',0)
            ->order('sort DESC')
            ->paginate(['page' => $page,'list_rows' => $size])
            ->toArray();
        return [HTTP_SUCCESS,$list];
    }

    public function goodsFind(int $id) : array{
        $data = IntegralGoods::with([
            'sku' => function($sql){
                $sql->with(['inventory']);
            }])
            ->find($id);
        return [HTTP_SUCCESS,$data];
    }

    public function orderFind(int $id) : array{
        $find = IntegralOrder::with(['orderCommodity' => function($sql){
            $sql->with(['goods','sellPrice','pvsValue']);
        },'store'])->find($id);
        return [HTTP_SUCCESS,$find];
    }


    public function orderList(int $page, int $size, array $data) : array{
        $where[] = ['status','>',0];
        $where[] = ['user_id','=',$this->user->id];
        !empty($data['start_time']) && $where[] = ['create_time','>=',$data['start_time']];
        !empty($data['end_time']) && $where[] = ['create_time','<=',$data['end_time']];
        $list = IntegralOrder::where($where)
            ->paginate(['page' => $page,'list_rows' => $size]);
        return [HTTP_SUCCESS,$list];
    }



    public function orderCreate(array $data, int $id, int $number, ?int $sku_id = 0){
        $user = $this->user;
        if (empty($user['status'])) throw new HttpException(HTTP_UNAUTH, "您已被拉黑，请联系管理员...");
        $address = [];
        if (!empty($data['store_id'])) {
            $store = Store::field('id,mobile,district,address')->find($data['store_id']);
            if (empty($store->id))
                throw new Exception('门店不存在',HTTP_NOTACCEPT);
            $address['order_type'] = 2;
            $address['store_id'] = $store->id;
            $address['iphone'] = $store->mobile;
            $address['address'] = str_replace($store->district.$store->address,',','');
        }else{
            if (!empty($data['user_address_id'])) {
                $address = $this->getAddressCode($data['user_address_id']);
            } else {
                $address['consignee'] = $data['consignee'];
                $address['iphone'] = $data['iphone'];
            }
        }
        $array = [];
        $data = [];
        $data['money'] = 0;
        $data['user_id'] = $user->id;
        $data['order_no'] = CreateNo::buildOrderNo($this->user->id);
        $data['order_no'];
        try{
            $commodity = IntegralGoods::lock(true)->find($id);
            if (empty($commodity))
                throw new Exception('商品不存在',HTTP_NOTACCEPT);
            $array['commodity_id'] = $id;
            $array['count'] = $number;
            $array['status'] = 0;
            $array['sku_id'] = $sku_id;
            $price = empty($sku_id) ?
                IntegralGoods::where('id', $commodity->id)->value('sell_price') :
                IntegralSkuInventory::where('sku_id',$sku_id)->value('sell_price');
            //$this->subInventoryByCount($commodity,$number, $sku_id);
            $array['money'] = floor($number*$price);
            $array['mall_id'] = $this->mid;
            $data['money'] = ceil($number * $price);
            $data['mall_id'] = $this->mid;
            $data['status'] = 0;
            unset($data['id']);
            $create = array_merge($data, $address);
            $res = IntegralOrder::create($create);
            $res->orderCommodity()->save($array);
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), HTTP_NOTACCEPT);
        }
        return [HTTP_SUCCESS, $res];

    }

    public function orderPay(int $order_id) : array{
        $order = IntegralOrder::with(['orderCommodity'])->find($order_id);
        if (empty($order))
            throw new Exception('订单不存在',HTTP_NOTACCEPT);
        if ($order->status != 0)
            throw new Exception('订单已经支付',HTTP_NOTACCEPT);
        $user = UserCash::where('user_id',$this->user->id)->lock(true)->find();
        if ($user->integral < $order->money)
            throw new Exception('积分不足', HTTP_NOTACCEPT);
        IntegralRecord::create(['mall_id' => $this->user->mall_id,'user_id' => $user->user_id,'order_id' => $order->id,'type' => 10,'status' => 1,'integral' => $order->money]);
        $this->subInventoryByCount(IntegralGoods::lock(true)->find($order->orderCommodity->commodity_id),$order->orderCommodity->count, $order->orderCommodity->sku_id);
        $status = 1;
        if ($order->order_type == 2)$status = 2;
        $order->save(['status' => $status]);
        $order->orderCommodity->save(['status' => $status]);

        $user->save(['integral' => $user->integral - $order->money,'integral_withdraw' => $user->integral_withdraw + $order->money]);
        return [HTTP_SUCCESS,$order];
    }


    public function orderReceiving(int $order_id) : array{
        $order = IntegralOrder::find($order_id);
        if (empty($order))
            throw new Exception('订单不存在',HTTP_NOTACCEPT);
        if ($order->status != 2)
            throw new Exception('订单不能收货',HTTP_NOTACCEPT);
        $order->save(['status' => 3]);
        $order->orderCommodity->save(['status' => 3,'receiving_time' => now()]);
        return [HTTP_SUCCESS,$order];

    }

    public function orderQrcode(int $id){
        global $mid;
        $qrcodeService = new QrcodeService();
        $stoer_id = IntegralOrder::where('id',$id)->value('store_id');
        list($code, $qrcode) = $qrcodeService->verification(['ids' => [$id],'a' => 2,'stoer_id' => $stoer_id,'mall_id' => $mid]);
        if ($code !== HTTP_SUCCESS)
            throw new Exception('二维码生成失败', HTTP_NOTACCEPT);
        return [$code,$qrcode];
    }


    public function storeList() : array{
        $list = Store::where('merchant_id',Merchant::where('is_self',1)->value('id'))->select();
        return [HTTP_SUCCESS,$list];
    }
//--------------
    private function getAddressCode(string $user_address_id)
    {
        $address = UserAddress::where('id', $user_address_id)
            ->where('mall_id', $this->mid)
            ->field('address,consignee,iphone')
            ->find()
            ->toArray();
        $address_arr = explode(',', $address['address']);
        $address_code = Area::where('name', $address_arr[0])->value('area_code');
        $address['code'] = $address_code;
        return $address;
    }
    public function subInventoryByCount(\think\Model $goods,int $count, int $skuId = null) : void
    {
        $goods->sell = $goods->sell + $count;
        if (empty($skuId)) {
            if ($goods->total < $count)
                throw new Exception('库存不足',HTTP_NOTACCEPT);
            // $goods->total = $goods->total - $count;
            $goods->save();
        } else {
            $goods->save();
            $sku = IntegralSkuInventory::lock(true)->where('sku_id',$skuId)->find();
            if ($sku->total < $count)
                throw new Exception('库存不足',HTTP_NOTACCEPT);
            $sku->total = $sku->total - $count;
            $sku->save();
        }
    }
}